package com.huang.springcloud.controller;

import com.huang.springcloud.pojo.Dept;
import com.huang.springcloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class DeptController {

    @Autowired
    DeptService deptService;

    @Autowired
    DiscoveryClient client;

    @PostMapping("/dept/add")
    public int addDept(@RequestBody Dept dept) {
        return deptService.addDept(dept);
    }

    @GetMapping("/dept/{id}")
    @HystrixCommand(fallbackMethod = "hystrixDept")
    public Dept getById(@PathVariable("id") int id) {
        Dept dept = deptService.getById(id);
        if (dept == null) {
            throw new RuntimeException("id =>" + id + "不存在");
        }
        return dept;
    }

    @GetMapping("/dept/list")
    @HystrixCommand(fallbackMethod = "hystrixDeptAll")
    public List<Dept> getList() {
        return deptService.getList();
    }

    //在服务端做熔断
    public Dept hystrixDept(@PathVariable("id") int id){
        return new Dept()
                .setDeptNo(id)
                .setDeptName("id =>" + id + "没有对应消息---@hystrix")
                .setDbSource("数据库不存在");

    }

    public List<Dept> hystrixDeptAll(){
        return new ArrayList<>();
    }

   /* 服务熔断：服务端 当某个服务超时或者异常，引起熔断。 保险丝
   *
   * 服务降级：客户端 从网站整体负载考虑，当某个服务熔断或者关闭之后，服务端不再被调用，此时客户端可以准备一下fallback factory，返回一个默认值。虽然网站整体服务下降了，但好歹能用
   *
   * */


}
